package com.sunday.scoremanager.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.event.EventBus;
import com.sunday.common.imageselector.MultiImageSelectorActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.utils.UploadUtils;
import com.sunday.common.widgets.ClearEditText;
import com.sunday.common.widgets.NoScrollGridView;
import com.sunday.scoremanager.R;
import com.sunday.scoremanager.adapter.GridAdapter;
import com.sunday.scoremanager.base.BaseApp;
import com.sunday.scoremanager.entity.Member;
import com.sunday.scoremanager.entity.Product;
import com.sunday.scoremanager.entity.UpLoadImg;
import com.sunday.scoremanager.http.ApiClient;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/10/27.
 */

public class AddProductActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.edit_pro_name)
    ClearEditText editProName;
    @Bind(R.id.edit_pro_desc)
    ClearEditText editProDesc;
    @Bind(R.id.edit_pro_price)
    ClearEditText editProPrice;
    @Bind(R.id.edit_pro_price_old)
    ClearEditText editProPriceOld;
    @Bind(R.id.grid_view)
    NoScrollGridView gridView;
    @Bind(R.id.edit_pro_discount)
    ClearEditText editProDiscount;

    private String productName, productMarketPrice, productPrice, productDesc;
    private ArrayList<String> imgList = new ArrayList<>();
    private GridAdapter adapter;
    private Long productId = null;
    private Member member;
    private Double defaultCommissionScale;
    private Product product;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_product);
        ButterKnife.bind(this);
        product = (Product) getIntent().getSerializableExtra("product");
        initView();
    }

    @Override
    public void back(View v) {
        intent = new Intent(mContext, ProductsManageActivity.class);
        startActivity(intent);
        finish();
    }

    private void initView() {
        titleView.setText(product == null ? "发布产品" : "修改产品");
        if (product != null) {
            editProName.setText(product.getProductName());
            editProDesc.setText(product.getProductDesc());
            editProPrice.setText(product.getProductPrice());
            editProPriceOld.setText(product.getMarketPrice());
            editProDiscount.setText(product.getSaleCount());
            imgList.clear();
            if (product.getImages() != null) {
                imgList.clear();
                imgList.addAll(product.getImages());
                netImgs.clear();
                netImgs.addAll(product.getImages());
                comPressImgList.clear();
                comPressImgList.addAll(product.getImages());
            }
        }
        adapter = new GridAdapter(mContext, imgList);
        gridView.setAdapter(adapter);
        adapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.img1:
                        int position = (int) v.getTag();
                        if (imgList.size() == position) {
                            selectImg();
                        }
                        break;
                    case R.id.img11:
                        int p = (int) v.getTag();
                        imgList.remove(p);
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        });
        member = BaseApp.getInstance().getMember();
        defaultCommissionScale = member.getCommissionScale();
        editProDiscount.setHint("默认最低" + (int) (defaultCommissionScale * 100));

    }


    private void selectImg() {
        intent = new Intent(mContext, MultiImageSelectorActivity.class);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        if (imgList != null && imgList.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, imgList);
        }
        startActivityForResult(intent, 0x1111);
    }

    private ArrayList<String> comPressImgList = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        imgList.clear();
        imgList.addAll(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT));
        adapter.notifyDataSetChanged();
        String imgs = null;
        for (int i = 0; i < imgList.size(); i++) {
            if (imgList.get(i).startsWith("http://")) {
                comPressImgList.add(imgList.get(i));
            } else {
                imgs = ImageUtils.getCompressImagePath(imgList.get(i));
                comPressImgList.add(imgs);
            }
        }
    }

    Integer commissionScale = null;

    @OnClick(R.id.btn_submit)
    void submit() {
        productName = editProName.getText().toString().trim();
        productDesc = editProDesc.getText().toString().trim();
        productPrice = editProPrice.getText().toString().trim();
        productMarketPrice = editProPriceOld.getText().toString().trim();
        String commscale = editProDiscount.getText().toString();
        if (!TextUtils.isEmpty(commscale) && Double.valueOf(commscale).compareTo(defaultCommissionScale * 100) < 0) {
            ToastUtils.showToast(mContext, "返积分折扣默认不低于" + (int) (defaultCommissionScale * 100));
            return;
        }
        commissionScale = TextUtils.isEmpty(commscale) ? (int) (defaultCommissionScale * 100) : Integer.valueOf(commscale);
        if (TextUtils.isEmpty(productName) || TextUtils.isEmpty(productDesc) || TextUtils.isEmpty(productPrice) ||
                TextUtils.isEmpty(productMarketPrice)) {
            ToastUtils.showToast(mContext, "内容不能为空");
            return;
        }
        if (comPressImgList != null && comPressImgList.size() > 0) {
            uploadImg();
        } else {
            ToastUtils.showToast(mContext, "请添加图片");
            return;
        }

    }


    List<String> netImgs = new ArrayList<>();

    private void uploadImg() {
        showLoadingDialog(0);
        Call<ResultDO<List<UpLoadImg>>> call = ApiClient.getApiAdapter().uploadImgs(UploadUtils.getRequestBody(comPressImgList));
        call.enqueue(new Callback<ResultDO<List<UpLoadImg>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<UpLoadImg>>> call, Response<ResultDO<List<UpLoadImg>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    netImgs.clear();
                    if (response.body().getResult() != null) {
                        for (UpLoadImg img : response.body().getResult()) {
                            if (img != null)
                                netImgs.add(img.getViewUrl());
                        }
                    }
                    saveProduct();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<UpLoadImg>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }


    private void saveProduct() {
        showLoadingDialog(0);
        long sellerId = BaseApp.getInstance().getMember().getSellerId();
        String img = "";
        if (!netImgs.isEmpty()) {
            img = netImgs.get(0);
        }
        Call<ResultDO<Product>> call = ApiClient.getApiAdapter().addProduct(productId, sellerId, productName,
                productMarketPrice, productPrice, productDesc, 0, img, StringUtils.listToString(netImgs), commissionScale);
        call.enqueue(new Callback<ResultDO<Product>>() {
            @Override
            public void onResponse(Call<ResultDO<Product>> call, Response<ResultDO<Product>> response) {
                if (isFinish) {
                    return;
                }
                dissMissDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "保存成功");
                    // EventBus.getDefault().post(new UpdateProMateria());
                    intent = new Intent(mContext, ProductsManageActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Product>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }


}
